//
//  WeekDayCollectionView.m
//  TableTest
//
//  Created by 众拳科技 on 2017/11/10.
//  Copyright © 2017年 众拳科技. All rights reserved.
//

#import "WeekDayCollectionView.h"
#import "WeekDayCollectionViewCell.h"
#import "WeekDayCollectionViewLayout.h"
#import "WeekDayTableViewCell.h"

@interface WeekDayCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource> {
    
}

@property(nonatomic,weak)UITableView *leftView;

@property(nonatomic,strong)NSMutableArray *bgColorArray;

@property(nonatomic,strong)NSMutableArray *titleColorArray;

@end

@implementation WeekDayCollectionView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self buildUI];
        
        self.bgColorArray = [[NSMutableArray alloc] init];
        
        [self.bgColorArray addObject:CSColorFromRGB(0xf7f7f7)];
        
        [self.bgColorArray addObject:CSColorFromRGB(0xffdd00)];
        
        [self.bgColorArray addObject:CSColorFromRGB(0x0a0a0a)];
        
        self.titleColorArray = [[NSMutableArray alloc] init];
        
        [self.titleColorArray addObject:CSColorFromRGB(0x323232)];
        
        [self.titleColorArray addObject:CSColorFromRGB(0x323232)];
        
        [self.titleColorArray addObject:CSColorFromRGB(0xffdd00)];
    }
    
    return self;
}

- (void)buildUI {
    
    [self addCollectionView];
}

- (void)addCollectionView {
    
    //避免UINavigation对UIScrollView产生的便宜问题
    [self addSubview:[UIView new]];
    
    /**
     CollectionView
     */
    WeekDayCollectionViewLayout *collectViewFlowLayout = [[WeekDayCollectionViewLayout alloc] init];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:collectViewFlowLayout];
    collectionView.showsHorizontalScrollIndicator = false;
    collectionView.backgroundColor = [UIColor whiteColor];
    [collectionView registerClass:[WeekDayCollectionViewCell class] forCellWithReuseIdentifier:@"WeekDayCollectionViewCell"];
    collectionView.userInteractionEnabled = true;
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self addSubview:collectionView];
    [collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
    
        make.edges.mas_equalTo(self);
    }];
    self.collectionView = collectionView;
    
    
    UITableView *leftView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    leftView.backgroundColor = [UIColor clearColor];
    [leftView registerClass:[WeekDayTableViewCell class] forCellReuseIdentifier:@"WeekDayTableViewCell"];
    leftView.delegate = self;
    leftView.dataSource = self;
    leftView.showsVerticalScrollIndicator = NO;
    [self addSubview:leftView];
    self.leftView = leftView;
    [leftView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(collectionView);
        make.width.mas_equalTo(SCREEN_WIDTH / 8 - 1);
    }];
    
}

#pragma mark -
#pragma mark CollectionDelegate

//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    WeekDayCollectionViewCell* weekDayCell = (WeekDayCollectionViewCell* )[collectionView cellForItemAtIndexPath:indexPath];
    
    _selectedIndex = indexPath.row;
    
    NSInteger row = indexPath.row / 8;
    
    NSInteger col = indexPath.row % 8;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentTimeString = [formatter stringFromDate:self.firstDayOfWeek];
    
    NSString *newTimeStr = [currentTimeString addDayWith:col - 1];
    
    NSString *rowStr = [NSString stringWithFormat:@"%02ld:00",row];
    
    /*
     * 排课打钩 选择日期
     *根据row得到具体的日期 YYYY年-MM月 用这个日期当Key
     *在这里要做判断，如果是横向的话就可以多选，纵向是不能多选的
     * 用右侧的时间当Key 00 - 24
     */
    if (weekDayCell.isHaveClass) {
        
        [NotificationCenter postNotificationName:@"HaveClassClick" object:nil userInfo:@{@"dayTime":newTimeStr,@"rowStr":rowStr}];
        
        //[MBProgressHUD showText:@"有课程"];
        
        return;
    }
    
    //如果是约课的情况下
    if ([self.gridType isEqualToString:@"Point"]) {
        
        return;
    }
    
    /*
    * 排课打钩 选择日期
    *根据row得到具体的日期 YYYY年-MM月 用这个日期当Key
    *在这里要做判断，如果是横向的话就可以多选，纵向是不能多选的
    * 用右侧的时间当Key 00 - 24
    */
    for (NSString *key in self.teachDict) {
        
        if ([key isEqualToString:rowStr]) {
            
            continue;
        }
        
        [self.teachDict removeObjectForKey:key];
    }
    
    NSMutableArray *timeArray = [self.teachDict objectForKey:rowStr];
    
    if (!timeArray) {
        
        timeArray = [[NSMutableArray alloc] init];
    }
    
    if ([timeArray containsObject:newTimeStr]) {
        
        [timeArray removeObject:newTimeStr];
    }
    else{
        
        [timeArray addObject:newTimeStr];
    }
    
    [self.teachDict setObject:timeArray forKey:rowStr];
    
    [collectionView reloadData];
    
    
    NSLog(@"时间:%02ld，星期:%ld",row,col - 1);
}

#pragma mark -
#pragma mark CollectionDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 192;//_items.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WeekDayCollectionViewCell* weekDayCell ;
    
    weekDayCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WeekDayCollectionViewCell" forIndexPath:indexPath];
    
    [weekDayCell resertColor];
    
    weekDayCell.row = indexPath.row;
    
    weekDayCell.betwCount = self.betwCount;
    
    
    /********排课处理********/
    NSInteger row = indexPath.row / 8;
    
    NSInteger col = indexPath.row % 8;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentTimeString = [formatter stringFromDate:self.firstDayOfWeek];
    
    NSString *newTimeStr = [currentTimeString addDayWith:col - 1];
    
    NSString *rowStr = [NSString stringWithFormat:@"%02ld:00",row];
    
    NSMutableArray *timeArray = [self.teachDict objectForKey:rowStr];
    
    if (timeArray) {
        
        if ([timeArray containsObject:newTimeStr]) {
            
            weekDayCell.isTeachSelect = YES;
        }
        else{
            
            weekDayCell.isTeachSelect = NO;
        }
    }
    else{
        
        weekDayCell.isTeachSelect = NO;
    }
    
    NSLog(@"teachDict = %@",self.teachDict);
    
    /********排课处理*******/
    
    
    /********显示处理*******/
    NSMutableArray *classArray = [self.hasTeachDict objectForKey:newTimeStr];
    
    for (NSDictionary *dict in classArray) {
     
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        
        NSDate *date = [formatter dateFromString:[dict objectForKey:@"BeginDateTime"]];
        
        [formatter setDateFormat:@"yyyy-MM-dd"];
        
        NSString *beginTime = [formatter stringFromDate:date];
        
        //顶部大日期相同，就代表这一天有排课
        if ([newTimeStr isEqualToString:beginTime]) {
            
            NSString *beginTime = [dict objectForKey:@"BeginDateTime"];
            
            NSString *endTime = [dict objectForKey:@"EndDateTime"];
            
            NSRange range = NSMakeRange(11, 2);
            
            NSRange minRange = NSMakeRange(14, 2);
            
            NSString *endKey = [endTime substringWithRange:range];
            
            NSString *beginKey = [beginTime substringWithRange:range];
            
            int endRow = [endKey intValue];
            
            int beginRow = [beginKey intValue];
            
            int beginMin = [[beginTime substringWithRange:minRange] intValue];
            
            int endMin = [[endTime substringWithRange:minRange] intValue];
            
            UIColor *bgColor = ((UIColor *)[self.bgColorArray objectAtIndex:col % 3]);
            
            UIColor *titleColor = ((UIColor *)[self.titleColorArray objectAtIndex:col% 3]);
            
            if (beginRow == row) {
                
                [weekDayCell resetAllCell];
                
                weekDayCell.beginMin = beginMin;
                
                weekDayCell.classNameLabel.text = [[dict objectForKey:@"CourseName"] isNull]?@"":[dict objectForKey:@"CourseName"];
                
                weekDayCell.classNameLabel.textColor = titleColor;
                
                weekDayCell.bgView.backgroundColor = bgColor;
                
                weekDayCell.bottomLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.topLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.isHaveClass = YES;
                
                weekDayCell.isTeachSelect = NO;
            }
            else if (row > beginRow && row < endRow - 1){
                
                [weekDayCell resetAllCell];
                
                weekDayCell.bgView.backgroundColor = bgColor;
                
                weekDayCell.bottomLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.topLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.isHaveClass = YES;
                
                weekDayCell.isTeachSelect = NO;
            }
            else if (endRow == row + 1){
                
                [weekDayCell resetAllCell];
                
                weekDayCell.bgView.backgroundColor =bgColor;
                
                weekDayCell.bottomLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.topLayer.backgroundColor = bgColor.CGColor;
                
                weekDayCell.placeNameLabel.text = [dict objectForKey:@"PlaceName"];
                
                weekDayCell.placeNameLabel.textColor = titleColor;
                
                weekDayCell.isHaveClass = YES;
                
                weekDayCell.isTeachSelect = NO;
                
            }
            //这里要算多出的ba
           else if (endRow == row) {

               if (endMin > 0) {
                   
                   weekDayCell.bgView.backgroundColor =bgColor;
                   
                   weekDayCell.topLayer.backgroundColor = bgColor.CGColor;
                   
                   weekDayCell.isHaveClass = YES;
                   
                   weekDayCell.isTeachSelect = NO;
                   
                   weekDayCell.endMin = endMin;
                   
                   weekDayCell.placeNameLabel.text = @"";
                   
                   weekDayCell.classNameLabel.text = @"";
               }
               else{
                   
                   [weekDayCell resetAllCell];
               }
           }
           else{
            
                [weekDayCell resetAllCell];
            }
            
            NSLog(@"beginTime = %@,endTime = %@,endMin = %d",beginTime,endTime,endMin);
            
        }
        else{
            
            //这一天都没有课
            [weekDayCell resetAllCell];
        }
        
    }
    
    //考虑到数组为0的情况，这时候要全部清空
    if (!classArray || classArray.count == 0) {
        
        [weekDayCell resetAllCell];
    }
    
    //NSLog(@"hasTeachDict = %@",self.hasTeachDict);
    /********显示处理*******/
    
    
    
    return weekDayCell;
}



#pragma mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WeekDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WeekDayTableViewCell"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


#pragma mark UITabelViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return ((SCREEN_WIDTH / 8) + 20) * 24;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    if ([scrollView isEqual:self.leftView]) {
        
        [self.collectionView setContentOffset:scrollView.contentOffset];
    }
    
    if ([scrollView isEqual:self.collectionView]) {
        
        [self.leftView setContentOffset:scrollView.contentOffset];
    }
}


//-(void)firstDayOfWeekChange:(NSNotification *)sender{
//
//    _betwCount = -1;
//
//    [_collectionView reloadData];
//
//}

#pragma mark Set
-(void)setBetwCount:(NSInteger)betwCount{
    
    _betwCount = betwCount;
    
    [_collectionView reloadData];
}

-(void)setHasTeachDict:(NSMutableDictionary *)hasTeachDict{
    
    _hasTeachDict = hasTeachDict;
    
    [_collectionView reloadData];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
